package top.eggcode.system.modules.user.control;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.web.bind.annotation.*;
import top.eggcode.common.base.SessionBaseController;
import top.eggcode.common.consts.ResponseStatus;
import top.eggcode.common.model.ResponseResult;
import top.eggcode.common.mvc.Responser;
import top.eggcode.system.modules.user.model.*;
import top.eggcode.system.modules.user.service.AuthService;
import top.eggcode.system.modules.user.service.SessionService;
import top.eggcode.system.modules.user.service.UserServiceImpl;

import java.util.LinkedList;
import java.util.Optional;

/**
 * Title: WEB 会话接口
 * Description: TODO
 * Date: 2021/5/18 8:06
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Api(tags = "系统会话")
@RequiredArgsConstructor
@RequestMapping("/api/session")
@RestController
public class SessionController extends SessionBaseController {

    private final SessionService sessionService;

    private final UserServiceImpl userService;

    private final AuthService authService;

    /**
     * shiro 获取sessionManager
     * 获取 token
     *
     * @param entity 账户信息
     * @return 令牌
     */
    @ApiOperation("登录")
    @PostMapping("/create")
    public ResponseResult<?> create(@RequestBody AccountLoginForm entity) {
        // 登录
        AccountEntity account = sessionService.login(entity.getUsername(), entity.getPassword()).get();

        // 创建会话
        /*        String token = (String) sessionService.create(account);*/

        SecurityUtils.getSubject().login(new UsernamePasswordToken(account.getUsername(), account.getPassword()));

        // 申请会话令牌
        SessionAuthenticationView authentication = new SessionAuthenticationView(SecurityUtils.getSubject().getSession().getId().toString());

        // 记录日志
        sessionService.addLoginLog(account.getUsername(), authentication.getSessionId());

        return Responser.successful(authentication);

    }

    @ApiOperation("注销")
    @DeleteMapping("/logout")
    public ResponseResult<?> logout() {
        return Responser.successful();
    }

    @ApiOperation("获取会话用户")
    @GetMapping("/user")
    public ResponseResult<?> getUserInfo() {
        String username = this.getUsername();
        Optional<UserBiz> box = userService.getByUsername(username);
        if (!box.isPresent()) {
            return Responser.failure("用户不存在");
        } else {

            UserBiz user = box.get();
            // 设置基本信息
            SessionUserView view = new SessionUserView();
            view.setId(user.getId());
            view.setMobile(user.getMobile());
            view.setUsername(user.getUsername());
            view.setNickname(user.getNickname());
            view.setAvatar(user.getAvatar());
            view.setSex(Short.valueOf(user.getSex()));
            view.setRoles(new LinkedList<>());
            view.setMenuPowers(new LinkedList<>());
            // 设置权限码
            view.setPowers(user.getPowers());
            return Responser.successful(view);
        }
    }

    /**
     * 刷新 token
     *
     * @param token 令牌
     * @return 令牌
     */
    @ApiOperation("刷新 token")
    @PutMapping("/token/refresh")
    public ResponseResult<?> refreshToken(@RequestHeader("X-Authorization") String token) {
        // 未携带 token
        if (StringUtils.isEmpty(token)) {
            Responser.failure(ResponseStatus.REQ_NO_TOKEN);
        }
        return super.pack(authService.refreshToken(token));
    }

}
